﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace Ku.Common
{
    public class EnumHelper
    {
        /// <summary>  
        /// 获取枚举类子项描述信息（注意：使用DescriptionAttribute这个类需要引入using System.ComponentModel;这个命名空间，别引错了。）  
        /// </summary>  
        /// <param name="enumSubitem">枚举类子项</param>          
        public static string GetEnumDescription(Enum enumSubitem)
        {
            string strValue = enumSubitem.ToString();

            var fieldinfo = enumSubitem.GetType().GetField(strValue);
            Object[] objs = fieldinfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (objs == null || objs.Length == 0)
            {
                return strValue;
            }
            else
            {
                DescriptionAttribute da = (DescriptionAttribute)objs[0];
                return da.Description;
            }

        }

        #region 获取枚举 列表表
        public static List<EnumProperty> GetEnumDescriptionList<T>()
        {
            List<EnumProperty> list = new List<EnumProperty>();
            var fields = typeof(T).GetFields();
            foreach (var item in fields)
            {
                try
                {
                    EnumProperty ep = new EnumProperty();
                    var field = item.GetValue(null);
                    ep.Key = field.ToString();
                    ep.Description = ep.Key;
                    ep.Value = (int)field;
                    Object[] objs = item.GetCustomAttributes(typeof(DescriptionAttribute), false);
                    if (objs != null && objs.Length > 0)
                    {
                        ep.Description = ((DescriptionAttribute)objs[0]).Description; ;
                    }

                    list.Add(ep);
                }
                catch  
                {
                }
            }
            return list;
        }
        #endregion

        /// <summary>
        /// 根据枚举 的key 获取value
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T? GetValueByKey<T>(string key) where T : struct, Enum
        {
            if (Enum.IsDefined(typeof(T), key))
            {
                return (T)Enum.Parse(typeof(T), key);
            }
            else
            {
                return null;
            }
        }
    }

    public class EnumProperty
    {
        public string Key { get; set; }
        public int Value { get; set; }

        public string Description { get; set; }
    }
}
